Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.
In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:
We'll lead you through each part which you'll implement in Python.
When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.
# TODO: Make all necessary imports.
import numpy as np
import pandas as pd
import cv2
import requests
import json
from datetime import datetime
from tensorflow.keras import Sequential
from tensorflow.python.keras.layers.core import Dense, Activation, Dropout, Flatten
from tensorflow.python.keras.layers.convolutional import Conv2D
from tensorflow.keras.optimizers import Adam, RMSprop
import tensorflow_hub as hub
from sklearn.utils import shuffle
from sklearn.preprocessing import LabelBinarizer
import tensorflow as tf
import tensorflow_datasets as tfds
import matplotlib.pyplot as plt
%matplotlib inline
# This lines are in case the normal tfds dataset has issues
#!pip --no-cache-dir install tfds-nightly==3.1.0.dev202005110105
#!pip --no-cache-dir install tfds-nightly
Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.
The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.
# Load the dataset with TensorFlow Datasets.
dataset, dataset_info = tfds.load('oxford_flowers102', with_info=True, as_supervised=True)
# print shapes of 3 firs images
for feature, label in dataset['train'].take(3):
print(feature.shape)
# Visualizing data
fig = plt.figure(figsize=(15,15))
i=0
for image, label in dataset['train'].take(5):
ax = fig.add_subplot(1,5,i+1)
ax.set_xticks([])
ax.set_yticks([])
plt.imshow(image)
plt.title(f"label: {label}")
plt.xlabel(f"img_shape: {image.shape}")
i=i+1;
fig.tight_layout()
As we can see above, images are not of same shape. Therefore, we will need to resize and normalize them.
# Print out dataset info
print(f"Number of training data points: {dataset_info.splits['train'].num_examples}")
print(f"Number of testing data points: {dataset_info.splits['test'].num_examples}")
print(f"Number of validation data points: {dataset_info.splits['validation'].num_examples}")
no_classes = dataset_info.features['label'].num_classes
print(f"number of classes: {no_classes}")
You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.
file_location='https://github.com/CheloGE/ML-tensorflow-Image_classifier-oxford_flowers102/blob/master/label_map.json?raw=1'
r = requests.get(file_location, stream=True)
class_names=json.loads(r.content.decode('utf-8'))
class_names = {int(k):v for k,v in class_names.items()}
# Visualizing first 5 training images
fig = plt.figure(figsize=(15,15))
i=0
for image, label in dataset['train'].take(5):
ax = fig.add_subplot(1,5,i+1)
ax.set_xticks([])
ax.set_yticks([])
plt.imshow(image)
plt.title(f"label: {class_names[label.numpy()+1]}")
plt.xlabel(f"img_shape: {image.shape}")
i=i+1;
fig.tight_layout()
def resize_image(image, size=(224,224)):
"""
This functions gets a bunch of images and resize them to the input size
@params size: desired size of the images
@params images: a tensor group of images to resize
@return resized_images: a numpy array with all new resized images
"""
return tf.image.resize(image, size)
def normalize_image(images, a=-1, b=1, minPix=[0], maxPix=[255]):
"""
Normalize the image data with Min-Max scaling to a range of [a, b]
@params images: a tensor of images data to be normalized
@return: tensor of Normalized image data
"""
a = tf.constant([a], dtype=tf.float32)
b = tf.constant([b], dtype=tf.float32)
min_pixel = tf.constant(minPix, dtype=tf.float32)
max_pixel = tf.constant(maxPix, dtype=tf.float32)
return a + (((images - min_pixel)*(b - a) )/(max_pixel - min_pixel))
def oneHotEncode(labels, no_classes):
"""
One hot encode Ordinal labels
@params labels: bunch of labels we want to hot encode
@return one hot encoded labels
"""
return tf.one_hot(labels, no_classes)
def flip(x):
"""Flip augmentation
Args:
x: Image to flip
Returns:
Augmented image
"""
x = tf.image.random_flip_left_right(x)
x = tf.image.random_flip_up_down(x)
return x
def rotate(x):
"""Rotation augmentation
Args:
x: Image
Returns:
Augmented image
"""
# Rotate 0, 90, 180, 270 degrees
return tf.image.rot90(x, tf.random.uniform(shape=[], minval=0, maxval=4, dtype=tf.int32))
def _preprocess_data(*vals):
"""
This function preprocess all data coming from each row of a tensorflow dataset type
"""
features = normalize_image(resize_image(vals[0]))
labels = oneHotEncode(vals[1], no_classes)
return features, labels
def _preprocess_data_augmentation(*vals):
"""
This function preprocess all data coming from each row of a tensorflow dataset type
"""
features = rotate(flip(normalize_image(resize_image(vals[0]))))
labels = oneHotEncode(vals[1], no_classes)
return features, labels
# Create a pipeline for each set based on batch
"""
Create batches of features and labels
batch(): saves the indexes of the data to be read once they are required, which does not fill ram unnecesary
shuffle(buffer_size): buffer_size -> size of samples pool for random selection // the higher the more
map(): functions that maps tensors list from Dataset to others values (good way do preprocessing tasks)
"""
batch_size = 128
buffer_size = 500
train_set = dataset['train'].shuffle(buffer_size).map(_preprocess_data_augmentation).batch(batch_size)
test_set = dataset['test'].map(_preprocess_data).batch(batch_size)
validation_set = dataset['validation'].map(_preprocess_data).batch(batch_size)
# Sanity check
print(f"training set shape: {np.array(list(train_set)).shape}")
print(f"testing set shape: {np.array(list(test_set)).shape}")
print(f"validation set shape: {np.array(list(validation_set)).shape}")
Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.
We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!
Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:
We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!
When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.
Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.
# network architecture
classifier_url ="https://hub.tensorflow.google.cn/google/tf2-preview/mobilenet_v2/feature_vector/4"
baseModel = hub.KerasLayer(classifier_url, input_shape=(224,224,3), output_shape=[1280], name="Mobilenet")
baseModel.trainable = False # freeze mobilenet weights
myModel = Sequential(name="Mobilenet_tranferLearning")
myModel.add(baseModel)
myModel.add(Dropout(0.5))
myModel.add(Activation("relu"))
myModel.add(Dense(102))
myModel.add(Activation("softmax"))
myModel.summary()
# Is GPU Avialable?
print('Is GPU Available?:', tf.test.is_gpu_available())
## Setting up optimizer
myModel.compile(Adam(lr=0.0008), 'categorical_crossentropy', ['accuracy'])
# Stop training when there is no improvement in the validation loss for 5 consecutive epochs
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)
## Parameters
Epochs = 25
## Start training
history = myModel.fit(train_set,
epochs=Epochs,
validation_data=validation_set,
callbacks=[early_stopping])
train_acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
train_loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(Epochs)
plt.figure(figsize=(20, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.
# Print the loss and accuracy values achieved on the entire test set.
# test data
result=myModel.evaluate(test_set)
print(f"test loss: {result[0]}, test accuracy: {result[1]}")
Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).
# Save your trained model as a Keras model.
today = datetime.now().strftime("%d_%m_%Y__%H_%M_%S")
saved_model_path = f"./saved_models/checkpoint_{today}"
myModel.save(saved_model_path, save_format='tf')
print(f"Model saved at: {saved_model_path}")
Load the Keras model you saved above.
# Load the Keras model
reloaded_model = tf.keras.models.load_model(saved_model_path)
reloaded_model.summary();
# Sanity check
image_batch, label_batch = train_set.take(1).__iter__().next()
image_batch = image_batch.numpy()
# predicting with the reloaded and current model.
result_batch = myModel.predict(image_batch)
reloaded_result_batch = reloaded_model.predict(image_batch)
# comparing both, if they are the same then the substraction should be 0.0
(abs(result_batch - reloaded_result_batch)).sum()
Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.
The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).
First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.
Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.
Finally, convert your image back to a NumPy array using the .numpy() method.
# TODO: Create the process_image function
def process_image(image):
"""
This function preprocess and image
"""
image = tf.convert_to_tensor(image, np.float32)
feature = normalize_image(resize_image(image))
return feature
To check your process_image function we have provided 4 images in the ./test_images/ folder:
The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.
from PIL import Image
from io import BytesIO
image_path = 'https://github.com/CheloGE/ML-tensorflow-Image_classifier-oxford_flowers102/blob/master/test_images/hard-leaved_pocket_orchid.jpg?raw=1'
response = requests.get(image_path, stream=True)
im = Image.open(BytesIO(response.content))
test_image = np.asarray(im)
processed_test_image = process_image(test_image)
fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(normalize_image(processed_test_image, 0, 1, [-1],[1]))
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()
Once you can get images in the correct format, it's time to write the predict function for making inference with your model.
Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.
# Create the predict function
def predict(image_path, model, top_k):
response = requests.get(image_path, stream=True)
im = Image.open(BytesIO(response.content))
test_image = np.asarray(im)
processed_test_image = process_image(test_image)
prediction = model.predict(np.expand_dims(processed_test_image, axis=0))
top_values, top_indices = tf.math.top_k(prediction, top_k)
top_classes = [class_names[value+1] for value in top_indices.cpu().numpy()[0]]
## Plotting images
fig = plt.figure(figsize=(15,10))
ax = fig.add_subplot(1,2,1)
plt.imshow(normalize_image(processed_test_image, 0, 1, [-1],[1]))
plt.title(f"Predicted label: {top_classes[0]}");
ax = fig.add_subplot(1,2,2)
plt.barh(top_classes, top_values.numpy()[0]*100)
fig.tight_layout(w_pad=5)
return top_values.numpy()[0], top_classes
It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:
In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.
# Plot the input image along with the top 5 classes
image_path = 'https://github.com/CheloGE/ML-tensorflow-Image_classifier-oxford_flowers102/blob/master/test_images/hard-leaved_pocket_orchid.jpg?raw=1'
predict(image_path, reloaded_model, 5);
# Plot the input image along with the top 5 classes
image_path = 'https://github.com/CheloGE/ML-tensorflow-Image_classifier-oxford_flowers102/blob/master/test_images/cautleya_spicata.jpg?raw=1'
predict(image_path, reloaded_model, 5);
# Plot the input image along with the top 5 classes
image_path = 'https://github.com/CheloGE/ML-tensorflow-Image_classifier-oxford_flowers102/blob/master/test_images/orange_dahlia.jpg?raw=1'
predict(image_path, reloaded_model, 5);
# Plot the input image along with the top 5 classes
image_path = 'https://github.com/CheloGE/ML-tensorflow-Image_classifier-oxford_flowers102/blob/master/test_images/wild_pansy.jpg?raw=1'
predict(image_path, reloaded_model, 5);
This script will help us predict new images based on command lines
%run -i 'predict.py'
%run -i 'predict.py' --top_k 3
%run -i 'predict.py' --image_url 'https://github.com/CheloGE/ML-tensorflow-Image_classifier-oxford_flowers102/blob/master/test_images/orange_dahlia.jpg?raw=1\' --top_k 7